package com.itheima.app.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.User;
import com.itheima.utils.ConstantUtil;
import com.itheima.utils.JwtUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

/**
 * @author Guanxing
 * @date 2021/9/19
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //放行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得token
        String token = request.getHeader("Authorization");
        //判断token是否有值
        if (StrUtil.isEmpty(token)) {
            response.setStatus(401); //返回权限不足
            return false;
        }
        //判断是否过期
        Boolean flag = stringRedisTemplate.hasKey(ConstantUtil.USER_TOKEN + token);
        if (!flag) {
            response.setStatus(401); //返回权限不足
            return false;
        }
        //解析token
        Map map = JwtUtil.parseToken(token);
        //将map转换为对象
        User user = BeanUtil.mapToBean(map, User.class, true);
        //若User解析错误
        if (user == null) {
            response.setStatus(401); //返回权限不足
            return false;
        }

        //此时token有效
        UserHolder.set(user);//绑定到线程上

        //查看是否冻结(限制登录)
        Boolean timeFlag = stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FREEZE_TIME, UserHolder.getId()));
        if (timeFlag) {
            //查看冻结范围
            String range = stringRedisTemplate.opsForValue().get(StrUtil.format(ConstantUtil.FREEZE_Range, UserHolder.getId()));
            if (StrUtil.equals("1", range)) { //冻结登录,登陆中踢下线
                response.setStatus(401);//返回权限不足(401)
                return false;
            }

        }

        //续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token,"1", Duration.ofDays(7));

        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();//删除线程的绑定
    }
}
